from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import (DjangoJobStore, register_events,
                                          register_job)

# 实例化调度器
scheduler = BackgroundScheduler()
# 调度器使用默认的DjangoJobStore()
scheduler.add_jobstore(DjangoJobStore(), 'default')

#修改任务
def modify_job(job_name,params):
    start_time = params['begin_time']  # 用户输入的任务开始时间, '10:00:00'
    start_time = start_time.split(':')
    hour = int(start_time[0])
    minute = int(start_time[1])
    temp_dict = {"hour":hour,"minute":minute}
    temp_trigger = scheduler._create_trigger(trigger='cron',trigger_args=temp_dict)
    scheduler.modify_job(job_name,trigger=temp_trigger)

# 增加定时任务
def add_job(func,params):
    start_time = params['begin_time']  # 用户输入的任务开始时间, '10:00:00'
    start_time = start_time.split(':')
    hour = int(start_time[0])
    minute = int(start_time[1])
    second = int(0)
    job_id = params['id']  
    job_name = params['name']
  
    # 创建任务
    scheduler.add_job(func, 'cron', hour=hour, minute=minute, second=second,id=job_id,name=job_name,args=[''])


#删除任务
def remove_job(job_name):
    scheduler.remove_job(job_name)
#暂停任务
def pause_job(job_name):
    scheduler.pause_job(job_name)
#开启任务
def resume_job(job_name,params):
    modify_job(job_name,params)
    scheduler.resume_job(job_name)


# 注册定时任务并开始
register_events(scheduler)
scheduler.start()